package com.qd.core.service;

import com.cdqidi.exception.ApiException;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.login.LoginBody;
import com.qd.core.service.login.LoginHolderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 系统登录
 *
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysLoginService {
    private final LoginHolderService loginHolderService;
    private final StringRedisTemplate stringRedisTemplate;

    @Transactional(readOnly = true)
    public Map<String, Object> login(LoginBody loginBody) {
        final String verifyKey = Constants.CAPTCHA_CODE_KEY + loginBody.getCaptchaId();
        final String captcha = stringRedisTemplate.opsForValue().get(verifyKey);
        if (!StringUtils.hasLength(captcha)) {
            throw new ApiException("验证码失效");
        }
        if (!loginBody.getCode().equalsIgnoreCase(captcha)) {
            throw new ApiException("验证码输入错误");
        }
        stringRedisTemplate.delete(verifyKey);
        if (log.isDebugEnabled()) {
            log.debug("userName: {},password: {}", loginBody.getUsername(), loginBody.getPassword());
        }
        return loginHolderService.login(loginBody, new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword()));
    }
}
